package com.hengda.museumonline.base;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.district.DistrictItem;
import com.amap.api.services.district.DistrictResult;
import com.amap.api.services.district.DistrictSearch;
import com.amap.api.services.district.DistrictSearchQuery;
import com.google.gson.Gson;
import com.hengda.museumonline.MyApplication;
import com.hengda.museumonline.R;
import com.hengda.museumonline.adapter.BaseLoadMoreHeaderAdapter;
import com.hengda.museumonline.adapter.BaseViewHolder;
import com.hengda.museumonline.adapter.EncAdapter;
import com.hengda.museumonline.adapter.ErrorAdapter;
import com.hengda.museumonline.entity.CategoryEvent;
import com.hengda.museumonline.entity.CityEvent;
import com.hengda.museumonline.entity.EngineeringBean;
import com.hengda.museumonline.entity.WikiBean;
import com.hengda.museumonline.http.CallServer;
import com.hengda.museumonline.http.GetData;
import com.hengda.museumonline.rxbus.RxBus;
import com.hengda.museumonline.ui.EncContentActivity;
import com.hengda.museumonline.ui.MainActivity;
import com.hengda.museumonline.ui.NewsContentActivity;
import com.hengda.museumonline.utils.CategorylistUtil;
import com.hengda.museumonline.utils.GridRefreshUtil;
import com.litesuits.common.utils.PackageUtil;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import java.util.List;

import rx.Observable;
import rx.functions.Action1;

public class EncPager {
    private MainActivity mainActivity;
    private RecyclerView recyclerview;
    private LinearLayout ll;
    private ImageView ivList;
    public View view;
    private EditText et_title;
    private CategorylistUtil util = null;
    private WikiBean wikiBean1 = new WikiBean();
    private WikiBean wikiBean2 = new WikiBean();
    private ImageView loading_bg;
    private MyAdapter mAdapter;
    private int i = 1;
    private Observable<CategoryEvent> observable;
    private int did;
    private String title;
    private int tag = 0;
    public EncPager(MainActivity activity) {
        mainActivity = activity;
        initView();
        initData();
    }

    private void initView() {
        view = View.inflate(mainActivity, R.layout.encpager, null);
        ll = (LinearLayout) view.findViewById(R.id.ll);
        ivList = (ImageView) view.findViewById(R.id.iv_list);
        loading_bg = (ImageView) view.findViewById(R.id.loading_bg);
        et_title = (EditText) view.findViewById(R.id.et_title);
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new GridLayoutManager(mainActivity, 2));
        //  recyclerview.setAdapter(new EncAdapter(mainActivity));
    }


    public void initData() {
        et_title.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if (et_title.getText().toString().equals("")) {
                        Toast.makeText(mainActivity, "请输入词条", Toast.LENGTH_SHORT).show();
                        return false;
                    } else {
                        title = et_title.getText().toString();
                        tag = 2;
                        getDataFromServer();
                        return false;
                    }
                }
                return false;
            }
        });

        util = new CategorylistUtil();
        ivList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                util.getCategorylistFromServer(mainActivity, ivList, "wiki/categorylist");
            }
        });

        observable = RxBus.get().register("category", CategoryEvent.class);
        observable.subscribe(new Action1<CategoryEvent>() {
            @Override
            public void call(CategoryEvent categoryEvent) {
                did = categoryEvent.getId();
                tag = 1;
                getDataFromServer();
                et_title.setText(categoryEvent.getCname());
            }
        });

        getDataFromServer();
    }

    private void getDataFromServer() {
        Request request;
        if (1 == tag) {
            request = NoHttp.createStringRequest(MyApplication.url + "wiki/categorytype", RequestMethod.GET);
            request.add("did", did);
        } else if (2 == tag) {
            request = NoHttp.createStringRequest(MyApplication.url + "wiki/searchinfo", RequestMethod.GET);
            request.add("title", title);
        } else {
            request = NoHttp.createStringRequest(MyApplication.url + "wiki/index", RequestMethod.GET);
        }
        request.add("p", "a");
        request.add("v", PackageUtil.getAppPackageInfo(mainActivity).versionName);
        request.add("offset", 0);
        request.add("size", 20);

        CallServer.getRequestInstance().add(mainActivity, 0, request, listener);
    }

    OnResponseListener listener = new OnResponseListener() {
        @Override
        public void onStart(int what) {

        }

        @Override
        public void onSucceed(int what, Response response) {
            int responseCode = response.getHeaders().getResponseCode();// 服务器响应码
            System.out.println("结果：" + "responseCode:" + responseCode + ",what:" + what + ",.....:" + response.get().toString());
            Gson gson = new Gson();
            if (0 == what) {
                System.out.println("结果：" + "responseCode:" + responseCode + ",what:" + what + ",.....:" + response.get().toString());
                wikiBean1 = gson.fromJson(response.get().toString(), WikiBean.class);
                if (wikiBean1 != null && wikiBean1.getData() != null && wikiBean1.getData().getList() != null && wikiBean1.getData().getList().size() > 0) {
                    loading_bg.setVisibility(View.INVISIBLE);
                    mAdapter = new MyAdapter(mainActivity, recyclerview, wikiBean1.getData().getList(), R.layout.enc_item);
                    recyclerview.setAdapter(mAdapter);
//                    GridRefreshUtil.onRefresh(mainActivity, ll, recyclerview);
//                    GridRefreshUtil.setOnRefreshListener(new GridRefreshUtil.OnRefreshListener() {
//                        @Override
//                        public void onPullDownRefresh() {
//                            GridRefreshUtil.onRefreshFinish();
//                        }
//                    });
                    mAdapter.setOnLoadMoreListener(new BaseLoadMoreHeaderAdapter.OnLoadMoreListener() {
                        @Override
                        public void onLoadMore() {
                            Request request;
                            if (1 == tag) {
                                request = NoHttp.createStringRequest(MyApplication.url + "wiki/categorytype", RequestMethod.GET);
                                request.add("did", did);
                            } else if (2 == tag) {
                                request = NoHttp.createStringRequest(MyApplication.url + "wiki/searchinfo", RequestMethod.GET);
                                request.add("title", title);
                            } else {
                                request = NoHttp.createStringRequest(MyApplication.url + "wiki/index", RequestMethod.GET);
                            }
                            request.add("p", "a");
                            request.add("v", PackageUtil.getAppPackageInfo(mainActivity).versionName);
                            request.add("offset", 20*i);
                            request.add("size", 20);

                            CallServer.getRequestInstance().add(mainActivity, 1, request, listener);

                        }
                    });
                } else {
                    recyclerview.setAdapter(new ErrorAdapter(mainActivity));
                }
            } else if (1 == what) {
                wikiBean2 = gson.fromJson(response.get().toString(), WikiBean.class);
                if (wikiBean2.getData() == null && wikiBean2.getData().getList() != null && wikiBean2.getData().getList().size() == 0) {
                    mAdapter.setLoading(false);
                } else {
                    mAdapter.addAll(wikiBean2.getData().getList());
                }
            }
        }

        @Override
        public void onFailed(int what, String url, Object tag, Exception exception, int responseCode, long networkMillis) {
            System.out.println("失败：" + "responseCode:" + responseCode + ",what:" + what + ",.....:" + exception);
            recyclerview.setAdapter(new ErrorAdapter(mainActivity));
        }

        @Override
        public void onFinish(int what) {

        }
    };

    class MyAdapter extends BaseLoadMoreHeaderAdapter<WikiBean.DataBean.ListBean> {

        public MyAdapter(Context mContext, RecyclerView recyclerView, List<WikiBean.DataBean.ListBean> mDatas, int mLayoutId) {
            super(mContext, recyclerView, mDatas, mLayoutId);
        }

        @Override
        public void convert(final Context mContext, RecyclerView.ViewHolder holder, final WikiBean.DataBean.ListBean listBean) {
            ((BaseViewHolder) holder).setText(R.id.title, listBean.getTitle());
            ((BaseViewHolder) holder).setImageUrl(R.id.image, listBean.getImage(), R.mipmap.cheese_5);
            ((BaseViewHolder) holder).setOnClickListener(R.id.enc_item, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Bundle bundle = new Bundle();
                    bundle.putString("did", listBean.getDid());
                    mainActivity.startActivity(mContext, EncContentActivity.class, bundle);
                }
            });
        }

    }
}
